<template>
    <Layout dis-hover>
        <div :style="{width: '100%',height: divHeight, }"><!--border: '1px solid #dcdee2'-->
            <Split v-model="split1">
                <div slot="left" class="demo-split-pane">
                    <Tree :data="treeData" :render="renderContent" ref="tree"></Tree>
                    <Dropdown trigger="click" style="margin-left:20px" placement="right-start"
                              ref="contentMenu" @on-click="selectTreeItem">
                        <DropdownMenu slot="list">
                            <DropdownItem name="addPoint" v-if="showPoint1">新增</dropdownitem>
                            <DropdownItem name="editPoint" v-if="showPoint">修改</dropdownitem>
                            <DropdownItem name="deletePoint" v-if="showPoint2">删除</dropdownitem>
                        </dropdownmenu>
                    </dropdown>
                </div>
                <div slot="right" class="demo-split-pane">
                    <Form :label-width="100" ref="formInline" :model="formInline" >
                        <Row :gutter="16" class="query-form" style="margin-left: 10px">
                            <i-col span="8">
                                <FormItem label="任务书内容：">
                                    <Input v-model="formInline.taskContent" placeholder="请输入任务书内容" />
                                </FormItem>
                            </i-col>
                            <i-col span="16">
                                <div>
                                    <Button class="ivu-btn-reset" @click="goback" icon="md-arrow-back">返回</Button>
                                    <Button class="ivu-btn-reset" @click="cancel">重置</Button>
                                    <Button class="ivu-btn-query" icon="md-search" @click="query()">查询</Button>
                                </div>
                            </i-col>
                        </Row>
                    </Form>
                    <Row type="flex" justify="start" v-show="!addButten && this.$attrs.buttonDisabled" class="query-form" style="margin-left: 10px">
                        <i-col>
                            <Button class="ivu-btn-add" icon="md-add" @click="add" >新增</Button>
                        </i-col>
                    </Row>
                    <Table ref='table' style="margin-top: 10px;margin-left: 10px" :loading="loading" border :columns="columns1"
                           :data="infos" width="100%" :height="tableHeight" highlight-row stripe size="small"></Table>
                    <Row type="flex" justify="end" style="margin-top: 10px">
                        <i-col>
                            <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
                                  @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
                        </i-col>
                    </Row>
                </div>
            </Split>
            <Modal v-model="modal1" title="任务书内容" width="600" :mask-closable="false">
                <Form ref="formCustom1" :model="form1data" :rules="ruleCustom" label-position="top" enctype ="multipart/form-data">
                    <Row>
                        <Col>
                            <FormItem label="任务书大类：" prop="taskType">
                                <Input v-model="form1data.taskType" readonly placeholder="请输入资料名称" />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col>
                            <FormItem label="任务书内容："  prop="taskContent">
                                <Input type="textarea" v-model="form1data.taskContent" placeholder="请输入任务书内容" show-word-limit :maxlength="500"/>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col>
                            <FormItem label="排序" prop="num">
                                <InputNumber :min="0" v-model="form1data.num" style="width: 100%" placeholder="请输入排序"></InputNumber>
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
                <div slot="footer">
                    <Button class='ivu-btn-save' :disabled="saveDissabled" @click="saveInfo">保存</Button>
                    <Button class='ivu-btn-cancel' @click="closeModal">取消</Button>
                </div>
            </Modal>


            <Modal v-model="isShow" :title="selectNodeInfo.title+(isUpdate?'  类型修改':'  类型新增')" width="600" :mask-closable="false" @on-cancel="isShow=false;formItem={}">
                <div style="margin: 0 20px" v-if="isShow">
                    <Form :model="formItem" ref="formCustom" :rules="ruleCustom">
                        <Row>
                            <i-col>
                                <FormItem label="任务书大类" prop="taskType">
                                    <Input type="text" v-model="formItem.taskType" placeholder="请输入任务书大类" show-word-limit :maxlength="25"></Input>
                                </FormItem>
                            </i-col>
                        </Row>
                        <Row>
                            <i-col>
                                <FormItem label="排序" prop="num">
                                    <InputNumber :min="0" v-model="formItem.num" style="width: 100%" placeholder="请输入排序"></InputNumber>
                                </FormItem>
                            </i-col>
                        </Row>
                    </Form>
                </div>
                <div slot="footer">
                    <Button class='ivu-btn-save' v-if="showEdit" :disabled="saveDissabled" @click="save">确定</Button>
                    <Button  class='ivu-btn-cancel' @click="isShow=false;formItem={}">取消</Button>
                </div>
            </Modal>

        </div>
    </Layout>
</template>

<script>

    import {Api} from '@/api/index.js'
    import {sessionStorage} from '@/common/cacheUtils.js';

    export default {
        name: "materialsTree",
        data(){
            return{
                currentUser: JSON.parse(sessionStorage('userId').get('userId')),
                isUpdate: false,
                tableHeight: '',
                divHeight: '',
                loading: false,
                split1: 0.27,
                treeData: [{
                    id : this.$attrs.taskBook.id,
                    name : this.$attrs.taskBook.companyName+'任务书',
                    title: this.$attrs.taskBook.companyName+'任务书',
                    parentId:'0',
                    num: 1,
                    expand:true,
                    children: []
                }],
                modal1: false,
                isShow:false,
                showEdit:false,
                formItem: {
                    name: ''
                },
                selectNodeInfo:{title:''},
                projectId: '',

                showPoint:false,
                showPoint1:true,
                showPoint2:false,
                formInline: {},
                form1data: {},
                columns1:[],
                columns: [
                    {type: 'index', title: '序号', width: 70, align: 'center',},
                    {title: '任务书大项', align: 'center', key: 'taskType',minWidth:130,},
                    {title: '任务书内容', align: 'center', key: 'taskContent',minWidth:150,tooltip:true},
                    {
                        title: '操作',
                        align: 'center',
                        width: '120',
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                        click: () => {
                                            this.update(params.row);
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {
                                        fontSize: '14px',
                                        color:'red',
                                    },
                                    on: {
                                        click: () => {
                                            this.delete(params.row);
                                        }
                                    }
                                }, '删除'),
                            ]);
                        }
                    },

                ],
                infos: [],
                pageSizeArray: [10, 20, 50],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1
                },
                ruleCustom: {
                    taskType: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur'
                    }],
                    num: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur',
                        type: 'number'
                    }],
                    taskContent: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur'
                    }]
                },
                addButten:true,
                saveDissabled:true
            }
        },
        watch:{
        },
        mounted(){
            this.divHeight = window.innerHeight -135 + 'px';
            this.tableHeight = window.innerHeight -250;
            this.queryTree();
            this.query();
        },
        methods:{
            goback(){
                this.$emit("close");
            },
            queryTree(){
                this.$http.get(Api.queryTaskBookType+ this.$attrs.taskBook.id).then((res) => {
                    res.data.data.forEach(m=>{
                        m.title = m.taskType
                        m.name = m.taskType
                        m.parentId = this.$attrs.taskBook.id
                    })
                    this.treeData.splice()
                    this.treeData[0].children = res.data.data;
                })
            },
            renderContent (h, { root, node, data }) {
                return h('span', {
                    style: {
                        display: 'inline-block',
                        cursor: 'pointer',
                    },
                    on: {
                        click: () => {
                            this.addButten=false
                            this.selectNodeInfo = data;
                            this.projectId = data.id;
                            this.formItem = {}
                            if (data.id === this.$attrs.taskBook.id) {
                                this.addButten=true
                                this.projectId = ''
                                // this.queryTree();
                                this.tableHeight = window.innerHeight -250;
                            }else {
                                this.tableHeight = window.innerHeight - (this.$attrs.buttonDisabled?290:250);
                            }
                            this.query();
                        },
                        contextmenu: (e) => {
                            if (this.$attrs.buttonDisabled) {
															  this.saveDissabled = false
                                if(data.parentId === this.$attrs.taskBook.id){
                                    this.showPoint = true;
                                    this.showPoint2 = true;
                                    this.showPoint1 = false;
                                }else{
                                    this.showPoint1 = true;
                                    this.showPoint = false;
                                    this.showPoint2 = false;
                                }
                                e.preventDefault();
                                this.selectNodeInfo = data;
                                this.selectNode = node;
                                this.selectRoot = root;
                                this.$refs.contentMenu.$refs.reference = event.target;
                                this.$refs.contentMenu.currentVisible = !this.$refs.contentMenu.currentVisible;
                            }
                        },
                    }
                }, [
                    h('span', [
                        // h('Icon', {
                        //     props: {
                        //         type: 'ios-folder-outline'
                        //     },
                        //     style: {
                        //         marginRight: '8px'
                        //     }
                        // }),
                        h('span', data.title)
                    ]),
                ]);
            },
            query(){
                const columns = [...this.columns];
                this.columns1 = []
                columns.forEach(item => {
                    if (!this.$attrs.buttonDisabled) {
                        if (item.title !=='操作') {
                            this.columns1.push(item)
                        }
                    } else {
                        this.columns1.push(item)
                    }
                })
                this.loading = true;
                let data = {
                    startPage: this.pagedata.currentPage,
                    size: this.pagedata.pageSize,
                    conditions: {
                        bookTypeId: this.projectId,
                        taskBookId: this.$attrs.taskBook.id,
                        taskContent: this.formInline.taskContent,
                    }
                };
                this.$http.post(Api.queryTaskBookContent,data).then((res) => {
                    this.infos = res.data.data.data;
                    this.pagedata.total = res.data.data.totalSize;
                    this.loading = false;
                }).catch( e => {
                    this.$Message.error('请求失败');
                });
            },
            cancel(){
                this.formInline = {};
                this.query();
            },
            add(){
							  this.saveDissabled = false
                this.isUpdate= false;
                this.modal1 = true;
                this.form1data={
                    projectId: this.selectNodeInfo.id,
                    taskType: this.selectNodeInfo.taskType,
                    num: this.infos.length +1
                }
            },

            update(row){
							  this.saveDissabled = false
                this.isUpdate= true;
                this.modal1 = true;
                this.form1data = row;
            },
            delete(row){
                this.$Modal.confirm({
                    title: '数据删除',
                    content: '<p>确定删除该数据</p>',
                    okText: '确认',
                    onOk: () => {
                        this.$http.delete(Api.deleteTaskBookContent + row.id).then((res) => {
                            this.query();
                            this.$Message.success({
                                content: '删除成功',
                                duration: 4
                            });
                        }).catch( e => {
                            this.$Message.error({
                                content: '请求失败',
                                duration: 4
                            });
                        });
                    }
                });
            },
            pageSizeChange(pageSize){
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            pageChange(pageNum){
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            selectTreeItem(name){
                if(name == 'addPoint'){
                    this.isUpdate = false;
                    this.showEdit = true;
                    this.isShow = true;
                    this.formItem.projectId = this.selectNodeInfo.id;
                    this.formItem.num = this.treeData[0].children.length +1
                }else if(name == 'editPoint'){
                    this.isUpdate = true;
                    this.showEdit = true;
                    this.isShow = true;
                    this.formItem = {
                        id: this.selectNodeInfo.id,
                        taskType: this.selectNodeInfo.title,
                        num: this.selectNodeInfo.num
                    }
                }else if(name == 'deletePoint'){
                    this.$Modal.confirm({
                        title: '数据删除',
                        content: '<p>确定删除该类别</p>',
                        okText: '确认',
                        onOk: () => {
                            let data = sessionStorage('userId').getObject('userId');
                            this.$http.delete(Api.deleteTaskBookType+this.selectNodeInfo.id).then((res) => {
                                if (res.data.status == 200) {
                                    this.projectId = ''
                                    this.queryTree();
                                    this.query();
                                    this.$Message.success({
                                        content: '删除成功',
                                        duration: 4
                                    });
                                }else {
                                    this.$Message.error({
                                        content: res.data.msg,
                                        duration: 4
                                    });
                                }
                            }).catch( e => {
                                this.$Message.error({
                                    content: '请求失败',
                                    duration: 4
                                });
                            });

                        },
                        cancelText: '取消'
                    });
                }
            },
            saveInfo(){
                this.$refs['formCustom1'].validate((valid) => {
                    if(valid) {
											  this.saveDissabled = true
                        let data = sessionStorage('userId').getObject('userId');
                        this.form1data.projectId = this.projectId;
                        if(this.isUpdate) {
                            this.form1data.updateUserId = data.userId;
                            this.$http.put(Api.updateTaskBookContent, this.form1data).then((res) => {
                                // this.queryTree(this.form1data.id);
                                this.query();
                                this.$Message.success({
                                    content: '保存成功',
                                    duration: 4
                                });
                                this.closeModal();
																this.saveDissabled = false
                            }).catch( e => {
															  this.saveDissabled = false
                                this.$Message.error({
                                    content: '请求失败',
                                    duration: 4
                                });
                            });
                        }else{
                            this.form1data.createUserId = data.userId;
                            this.$http.post(Api.saveTaskBookContent, this.form1data).then((res) => {
                                // this.queryTree();
                                this.query();
                                this.$Message.success({
                                    content: '保存成功',
                                    duration: 4
                                });
                                this.closeModal();
																this.saveDissabled = false
                            }).catch( e => {
															this.saveDissabled = false
                                this.$Message.error({
                                    content: '请求失败',
                                    duration: 4
                                });
                            });
                        }
                    }
                });
            },
            closeModal(){
                this.modal1 = false;
                this.form1data = {};
            },
            save(){
                this.$refs['formCustom'].validate((valid) => {
                    if(valid) {
											this.saveDissabled = true
                        let data = sessionStorage('userId').getObject('userId');
                        this.formItem.projectId = this.$attrs.taskBook.id
                        if(this.isUpdate) {
                            this.formItem.updateUserId = data.userId;
                            this.$http.put(Api.updateTaskBookType, this.formItem).then((res) => {
                                this.queryTree();
                                this.isShow = false;
                                this.$Message.success({
                                    content: '保存成功',
                                    duration: 4
                                });
																this.saveDissabled = false
                            }).catch( e => {
                                this.$Message.error({
                                    content: '请求失败',
                                    duration: 4
                                });
																this.saveDissabled = false
                            });
                        }else{
                            this.formItem.createUserId = data.userId;
                            this.$http.post(Api.saveTaskBookType, this.formItem).then((res) => {
                                this.queryTree();
                                this.isShow = false;
                                this.$Message.success({
                                    content: '保存成功',
                                    duration: 4
                                });
																this.saveDissabled = false
                            }).catch( e => {
                                this.$Message.error({
                                    content: '请求失败',
                                    duration: 4
                                });
																this.saveDissabled = false
                            });
                        }
                    }
                });
            },
        }
    }
</script>

<style scoped>
    @import '../../../index.css';
</style>
